﻿using Sidvall.WorkItemManager.Data;
using Sidvall.WorkItemManager.Data.Fields;
using System.Threading.Tasks;

namespace Sidvall.WorkItemManager.Model.Local.DataPortalManagers
{
    public static partial class WorkItemSensorManager
    {
        static partial void OnBeforeExecute(IDataPortalManager dataPortalManager, Sidvall.Business.DataPortalContext<Sidvall.Data.CommandCriteria, Sidvall.Data.CommandCriteria> dataPortalContext)
        {
            dataPortalContext.Tasks.Add(OnBeforeExecuteTask(dataPortalManager, dataPortalContext));
        }
        private static async Task OnBeforeExecuteTask(IDataPortalManager dataPortalManager, Sidvall.Business.DataPortalContext<Sidvall.Data.CommandCriteria, Sidvall.Data.CommandCriteria> dataPortalContext)
        {
            SensorValueCollection sensors;
            long id;

            switch (dataPortalContext.OperationContext.CriteriaId)
            {
                case ParameterManager.WorkItemSensorGetParameterName:
                    id = dataPortalContext.OperationContext.Parameters.ValueToNullableInt64(WorkItemField.WorkItemId.ToString()).Value;
                    if (!await Sidvall.SystemContext.Current.AuthorizationManager.IsAuthorizedAsync(Sidvall.WorkItemManager.Data.Model.DomainObjects.WorkItemSensor,
                        Sidvall.Security.Operations.Execute, dataPortalContext.OperationContext.CriteriaId, id.ToString()).ConfigureAwait(false))
                    {
                        throw new Sidvall.Security.UnauthorizedException();
                    }
                    break;
                case ParameterManager.WorkItemSensorUpdateParameterName:
                    sensors = dataPortalContext.OperationContext.Parameters.ValueToObject<SensorValueCollection>(ParameterManager.SensorsParameterName, null);
                    if ((sensors == null) || (sensors.Count == 0))
                    {
                        dataPortalContext.Result = Sidvall.Business.DataPortalResult.Skipped;
                    }
                    else
                    {
                        id = dataPortalContext.OperationContext.Parameters.ValueToNullableInt64(WorkItemField.WorkItemId.ToString()).Value;
                        if (!await Sidvall.SystemContext.Current.AuthorizationManager.IsAuthorizedAsync(Sidvall.WorkItemManager.Data.Model.DomainObjects.WorkItemSensor,
                            Sidvall.Security.Operations.Execute, dataPortalContext.OperationContext.CriteriaId, id.ToString()).ConfigureAwait(false))
                        {
                            throw new Sidvall.Security.UnauthorizedException();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }
}